package gcommand

/*******************************************************************************
Copyright:cloud
Author:cloudapex@126.com
Version:1.0
Date:2014-10-18
Description:主视图窗口
	1 调用Create(mode)
	2 调用Run()
	2 init window and bind mode
	3 调用control相关控制接口
*******************************************************************************/
import (
	. "Ghost/utd"
	"Ghosted/pack"
	"fmt"
	"github.com/lxn/walk"
	. "github.com/lxn/walk/declarative"
	"github.com/lxn/win"
	"strings"
)

var TheView *MainView = &MainView{}

type MainView struct {
	*walk.MainWindow

	centerTbl *walk.TableView
	nodeTbl   *walk.TableView
	tabWidget *walk.TabWidget
	inputCB   *walk.ComboBox

	curCenterNode *pack.PtNetNode
	curNodeNode   *pack.PtNetNode

	mapTabData map[*walk.TabPage]*pack.PtNetNode
	mapDataTab map[string]*walk.TextEdit

	isSpecialMode *walk.MutableCondition
}

func (this *MainView) Create(mainModel IMainModeler) {

	this.isSpecialMode = walk.NewMutableCondition()
	MustRegisterCondition("isSpecialMode", this.isSpecialMode)

	this.mapTabData = make(map[*walk.TabPage]*pack.PtNetNode)
	this.mapDataTab = make(map[string]*walk.TextEdit)

	var databind *walk.DataBinder

	if err := (MainWindow{
		AssignTo:   &this.MainWindow,
		Title:      "GhostCommand",
		Visible:    false,
		DataBinder: DataBinder{AssignTo: &databind, DataSource: mainModel, AutoSubmit: true},
		ToolBar: ToolBar{
			ButtonStyle: ToolBarButtonImageOnly,
			Items: []MenuItem{
				Menu{
					Text:  "MenuAction",
					Image: "../img/document-new.png",
					Items: []MenuItem{
						Action{
							Text: "A",
							//OnTriggered: this.newAction_Triggered,
						},
						Action{
							Text: "B",
							//OnTriggered: this.newAction_Triggered,
						},
						Action{
							Text: "C",
							//OnTriggered: this.newAction_Triggered,
						},
					},
					//OnTriggered: this.newAction_Triggered,
				},
				Action{
					Text:  "Action32*32",
					Image: "../img/32_portrait138.png",
					//OnTriggered: this.newAction_Triggered,
				},
				Action{
					Text:        "&W关闭当前Tab页面",
					Image:       "../img/32_portrait138.png",
					Shortcut:    Shortcut{walk.ModControl, walk.KeyQ},
					OnTriggered: this.CloseActionCurrentTab,
				},
			},
		},
		MinSize: Size{800, 600},
		Layout:  VBox{MarginsZero: true, SpacingZero: true},

		Children: []Widget{
			HSplitter{HandleWidth: 2, Children: []Widget{ // 左右分割
				// 左边|上下分割
				VSplitter{StretchFactor: 2, HandleWidth: 2, Children: []Widget{
					Composite{StretchFactor: 1, Layout: VBox{MarginsZero: true, SpacingZero: true}, Children: []Widget{
						LineEdit{Text: "过滤Center列表"},
						TableView{
							AssignTo: &this.centerTbl,
							Model:    mainModel.CenterTableModel(),
							AlternatingRowBGColor: walk.RGB(255, 255, 200),
							ColumnsOrderable:      true,
							OnCurrentIndexChanged: this.OnCenterTableCurrentIndexChanged,
							OnItemActivated:       this.OnCenterTableItemActivated,
							Columns: []TableViewColumn{
								{Name: "ID", DataMember: "ServerID", Width: 52},
								{Name: "Name", DataMember: "ServerName", Width: 76},
								{Name: "IP", DataMember: "ListenIP", Width: 126},
							},
						},
					}},
					Composite{StretchFactor: 2, Layout: VBox{MarginsZero: true, SpacingZero: true}, Children: []Widget{
						LineEdit{Text: "过滤Node列表"},
						TableView{
							AssignTo: &this.nodeTbl,
							Model:    mainModel.NodeTableModel(),
							AlternatingRowBGColor: walk.RGB(255, 255, 200),
							ColumnsOrderable:      true,
							OnCurrentIndexChanged: this.OnNodeTableCurrentIndexChanged,
							OnItemActivated:       this.OnNodeTableItemActivated,
							Columns: []TableViewColumn{
								{Name: "ID", DataMember: "ServerID", Width: 52},
								{Name: "Name", DataMember: "ServerName", Width: 76},
								{Name: "IP", DataMember: "ListenIP", Width: 126},
							},
						},
					}},
				}},
				// 右边
				Composite{StretchFactor: 4, Layout: VBox{MarginsZero: true, SpacingZero: true}, Children: []Widget{
					Composite{ // 概览信息
						MaxSize: Size{0, 60},
						Layout:  HBox{MarginsZero: true, SpacingZero: true}, Children: []Widget{
							TextEdit{
								Text:    Bind("ServerInfo"),
								Enabled: false,
							},
							Composite{Layout: VBox{MarginsZero: true}, Children: []Widget{
								PushButton{
									MinSize: Size{0, 61},
									Text:    "刷新",
								}},
							},
						},
					},
					Composite{StretchFactor: 100, // tab页
						Layout: VBox{MarginsZero: true, SpacingZero: true}, Children: []Widget{
							TabWidget{AssignTo: &this.tabWidget},
						},
					},
					Composite{ // 控制输入
						MaxSize: Size{0, 51},
						Layout:  HBox{MarginsZero: true, SpacingZero: true},
						Children: []Widget{
							Composite{Layout: VBox{Margins: Margins{0, 6, 0, 0}}, Children: []Widget{
								ComboBox{
									AssignTo:  &this.inputCB,
									Font:      Font{Family: "微软雅黑", PointSize: 16},
									Model:     mainModel.CmdInputModel(),
									Editable:  true,
									OnKeyDown: this.OnCombKeyDown,
								},
							}},
							Composite{Layout: VBox{MarginsZero: true}, Children: []Widget{
								PushButton{
									MinSize:   Size{0, 38},
									Text:      "发  送",
									OnClicked: this.OnBtnSendClicked,
								},
							}},
						},
					},
				}}},
			},
		},
	}.Create()); err != nil {
		UMain.Fatal(err)
	}
	TheModel.dbind = databind
	if err := walk.InitWrapperWindow(this); err != nil {
		UMain.Fatal(err)
	}
}

func (this *MainView) WndProc(hwnd win.HWND, msg uint32, wParam, lParam uintptr) uintptr {
	switch msg {
	case win.WM_WINDOWPOSCHANGED:
		if this.X() == 0 || this.Y() == 0 {
			break
		}
		TheCtrl.SaveWinPos(this.X(), this.Y())
	}
	return this.MainWindow.WndProc(hwnd, msg, wParam, lParam)
}
func (this *MainView) InitNodeList() {
	this.curCenterNode = TheModel.centers.items[0]
	this.curNodeNode = TheModel.nodes.items[0]
}
func (this *MainView) OnCenterTableCurrentIndexChanged() {}

func (this *MainView) OnCenterTableItemActivated() {
	this.curCenterNode = TheModel.centers.items[this.centerTbl.CurrentIndex()]

	TheCtrl.UpdateNodeList(this.centerTbl.CurrentIndex())
}

func (this *MainView) OnNodeTableCurrentIndexChanged() {}

func (this *MainView) OnNodeTableItemActivated() {
	this.curNodeNode = TheModel.nodes.items[this.nodeTbl.CurrentIndex()]
	this.OpenCommandPage(this.nodeTbl.CurrentIndex())
}
func (this *MainView) OnCombKeyDown(key walk.Key) {
	if key != walk.KeyReturn {
		return
	}
	this.OnBtnSendClicked()
}
func (this *MainView) OnBtnSendClicked() {
	if this.tabWidget.Pages().Len() <= 0 {
		return
	}
	curPage := this.tabWidget.Pages().At(this.tabWidget.CurrentIndex())
	if value, exist := this.mapTabData[curPage]; exist {
		TheCtrl.SendAdminCommand(this.curCenterNode.ServerId, value, this.inputCB.Text())
	}
}
func (this *MainView) OpenCommandPage(index int) error {

	pageName := fmt.Sprintf("%d|%d", this.curCenterNode.ServerId, this.curNodeNode.ServerId)
	if outpage, exist := this.mapDataTab[pageName]; exist {
		n := this.tabWidget.Pages().Index(outpage.Parent().(*walk.TabPage))
		this.tabWidget.SetCurrentIndex(n)
		return nil
	}
	page, err := walk.NewTabPage()
	if err != nil {
		return err
	}
	page.SetLayout(walk.NewHBoxLayout())

	page.SetTitle(this.curNodeNode.ServerName)
	page.SetName(pageName)

	outpage, err := walk.NewTextEdit(page)
	if err != nil {
		return err
	}
	outpage.SetReadOnly(true)
	this.mapDataTab[page.Name()] = outpage
	this.mapTabData[page] = this.curNodeNode
	// 添加
	if err := this.tabWidget.Pages().Add(page); err != nil {
		return err
	}
	// 设置显示Index
	if err := this.tabWidget.SetCurrentIndex(this.tabWidget.Pages().Len() - 1); err != nil {
		return err
	}

	return nil
}
func (this *MainView) CloseActionCurrentTab() {

	if this.tabWidget.Pages().Len() <= 0 {
		return
	}

	curPage := this.tabWidget.Pages().At(this.tabWidget.CurrentIndex())
	delete(this.mapDataTab, curPage.Name())
	delete(this.mapTabData, curPage)

	if this.tabWidget.Pages().Len() == 1 {
		this.tabWidget.Pages().Clear()
	} else {
		this.tabWidget.Pages().RemoveAt(this.tabWidget.CurrentIndex())
		this.tabWidget.SetCurrentIndex(this.tabWidget.Pages().Len() - 1)
	}
}
func (this *MainView) ShowAdminCommand(centerId, NodeId int32, info string) {
	if value, exist := this.mapDataTab[fmt.Sprintf("%d|%d", centerId, NodeId)]; exist {
		info = strings.Replace(info, "\n", "\r\n", -1)
		value.AppendText(info)
	}
}
